from urllib.request import Request

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from coures.courseser import CourseSer
from coures.models import CourseModel
from home import models
from home.NavSer import NavSer, BannerSer, CateSer
from home.models import BannerModel


# Create your views here.
# 页面上部分导航查询
class Toy(APIView):
    def get(self, request):
        vane = models.NavModel.objects.filter(is_del=0, position=1).order_by("order")
        nae = NavSer(vane, many=True)
        return Response({"msg": "ok", "code": 200, "data": nae.data})


# 页面下部分导航查询
class FooB(APIView):
    def get(self, request):
        vane = models.NavModel.objects.filter(is_del=0, position=0).order_by("order")
        nae = NavSer(vane, many=True)
        return Response({"msg": "ok", "code": 200, "data": nae.data})


# 首页轮播图
class BannerAPI(APIView):
    def get(self, request):
        vane = models.BannerModel.objects.filter(is_del=0).order_by('order')
        nae = BannerSer(vane, many=True)
        return Response({"msg": "ok", "code": 200, "data": nae.data})


# 首页黑框标题展示
class CategoryAPI(APIView):
    def get(self, request):
        vane = models.cateModel.objects.filter(is_del=0, is_home=1, parent=None).order_by('order')
        nae = CateSer(vane, many=True)
        for i in nae.data:
            i['children'] = i['children'][:3]
        return Response({"msg": "ok", "code": 200, "data": nae.data})


# 选择黑框标题下的详细数据展示
class CateFindById(APIView):
    def get(self, request):
        # 展示一级标题
        vane = models.cateModel.objects.filter(is_del=0, id=request.query_params.get("id")).first()
        nae = CateSer(vane)
        # 展示二级标题
        vane1 = models.cateModel.objects.filter(is_del=0, parent=request.query_params.get("id"))
        catelist = []
        for i in vane1:
            catelist.append(i.id)
        #     展示图片信息
        vane2 = CourseModel.objects.filter(is_del=0, category__in=catelist, ishome=1).order_by("order")
        nae2 = CourseSer(vane2, many=True)
        mydata = nae.data
        mydata['course'] = nae2.data[:4]

        return Response({"msg": "ok", "code": 200, "data": mydata})
